package edu.cmu.cs.webapp.ioms.actions.product;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;

import edu.cmu.cs.webapp.ioms.dao.DataAccessException;
import edu.cmu.cs.webapp.ioms.dao.impl.IngredientDAOImpl;
import edu.cmu.cs.webapp.ioms.models.Ingredient;
import edu.cmu.cs.webapp.ioms.ui.wizards.ingredient.IngredientWizard;
import edu.cmu.cs.webapp.ioms.views.IngredientInfoView;
import edu.cmu.cs.webapp.ioms.views.IngredientListView;
import edu.cmu.cs.webapp.ioms.views.OrderDetailsView;

public class EditIngredientViewAction implements IViewActionDelegate {

	private Ingredient model;
	private IngredientInfoView _view;

	@Override
	public void init(IViewPart view) {
		this._view = (IngredientInfoView) view;
	}

	@Override
	public void run(IAction action) {
		if (this.model != null) {
			IngredientWizard wizard = new IngredientWizard(true, model);

			wizard.setWindowTitle("Edit Product Information");
			WizardDialog dialog = new WizardDialog(_view.getViewSite()
					.getShell(), wizard);
			dialog.setBlockOnOpen(true);
			dialog.open();

			// just either ok or cancel
			int returnCode = dialog.getReturnCode();

			if (returnCode == org.eclipse.jface.window.Window.OK) {
				// edit order
				// DAO goes here
				try {
					new IngredientDAOImpl().updateIng(wizard.getModel());
					
					this._view.refreshIngredientsView();
					IngredientListView.getFormulaListViewPart(
							this._view.getViewSite()).refIngrListView();

				} catch (DataAccessException e) {
					System.out.println(e.getStackTrace());
				}

			}

		}

	}

	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// for testing purpose, using the purchaesorder class

			if (obj instanceof Ingredient) {
				// manually create a new product
				this.model = (Ingredient) obj;
			}
		}
	}

}
